//
//  CreateNewHomeViewController.m
//  AILock
//
//  Created by 谭亚明 on 2020/6/22.
//  Copyright © 2020 tym. All rights reserved.
//

#import "CreateNewHomeViewController.h"
#import "UIView+ZFFrame.h"
#import "UserService.h"
#import "Sizes.h"
#import "YPVideoPickerViewController.h"
#import "UIimage+Extends.h"
#import "Colors.h"
#import "UIButton+Gradient.h"
#import "WHToast.h"
#import "HXPhotoManager.h"
#import "FamilyService.h"
@interface CreateNewHomeViewController ()<HXPhotoViewControllerDelegate>

@property(nonatomic,weak) IBOutlet UIView *contView;

@property(nonatomic,weak) IBOutlet UIImageView *headImage;
@property(nonatomic,copy) NSString *headStr;
@property(nonatomic,weak) IBOutlet UITextField *familyNameFid;
@property(nonatomic,weak) IBOutlet UITextField *familyDicFid;
@property(nonatomic,strong) FamilyService *familyService;

@property (strong, nonatomic) HXPhotoManager *manager;//相册manager
@end

@implementation CreateNewHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"创建新家庭"];
    [self initUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
}

-(FamilyService*)familyService{
    if (_familyService == nil) {
        _familyService = [[FamilyService alloc] init];
    }
    return _familyService;
}

-(void)initUI{
    self.contView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
    self.contView.layer.cornerRadius = 4.5;
    self.contView.layer.shadowColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.5].CGColor;
    self.contView.layer.shadowOffset = CGSizeMake(0,0);
    self.contView.layer.shadowOpacity = 1;
    self.contView.layer.shadowRadius = 14;
    
    self.headImage.layer.masksToBounds = YES;
    self.headImage.layer.cornerRadius = self.headImage.frame.size.height/2;
    
    self.createBtn.layer.cornerRadius = 5;
    self.createBtn.layer.masksToBounds = YES;
    self.createBtn.zf_width = ScreenWidth - 60;
    [self changedTextField:nil];
    
    [self.familyNameFid addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
    [self.familyDicFid addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
}

-(void)changedTextField:(UITextField*)textField{
    if (textField == self.familyNameFid) {
        if (textField.text.length > 8) {
            UITextRange *markedRange = [textField markedTextRange];
            if (markedRange) {
                return;
            }
            NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:8];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
    if (textField == self.familyDicFid) {
        if (textField.text.length > 20) {
            UITextRange *markedRange = [textField markedTextRange];
            if (markedRange) {
                return;
            }
            NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:20];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
    
    if (self.familyNameFid.text.length < 1) {
        [self.createBtn setBackgroundImage:[UIImage imageWithColor:rgba(230, 230, 230) withSize:self.createBtn.bounds.size] forState:UIControlStateNormal];
    }else{
        [self.createBtn gradientButtonWithSize:CGSizeMake(300, 44) colorArray:@[(id)rgba(139, 175, 255),(id)rgba(76, 132, 255)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    }
}

-(IBAction)doSeleImageAction:(id)sender{
    
    self.manager.type  = HXPhotoManagerSelectedTypePhoto;
    self.manager.configuration.openCamera = YES;
    YPVideoPickerViewController *vc = [[YPVideoPickerViewController alloc] init];
    vc.manager = self.manager;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)doCreatFamilyAction:(id)sender{
    
    if (self.familyNameFid.text.length < 1) {
        [WHToast showMessage:@"请输入家庭名称" duration:2 finishHandler:nil];
        return;
    }
    
    TYMWeak(self);
    [self.familyService getCreatFamilyWithFamilyName:self.familyNameFid.text desc:self.familyDicFid.text image:self.headStr completion:^(NSError * _Nonnull error, LMJBaseResponse *response) {
        if (!error) {
            [WHToast showMessage:@"家庭创建成功" duration:2 finishHandler:^{
                [weakself.navigationController popToRootViewControllerAnimated:YES];
            }];
        }
    }];
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)personalUploadHeadImgInterfaceWithImage:(UIImage *)uploadImage  {
    //网络请求管理器
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", BaseUrl,  urlImageUpload];
    [sessionManager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", [UserTool getLogInUser].token, str];
        [formData appendPartWithFileData:imageData name:@"file"  fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject[@"code"] integerValue]) {
            self.headStr = responseObject[@"data"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHToast showMessage:@"上传图片失败" duration:2 finishHandler:nil];
    }];
}

#pragma mark - 懒加载选择视频的manager
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
        _manager.configuration.openCamera = NO;
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.maxNum = 1;
        _manager.configuration.photoCanEdit = NO;
        _manager.configuration.hideOriginalBtn = YES;
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.replacePhotoEditViewController = NO;
        _manager.configuration.replaceVideoEditViewController = NO;
        _manager.configuration.showBottomPhotoDetail = NO;
        _manager.configuration.themeColor = [UIColor blackColor];
        _manager.configuration.navBarBackgroudColor = [UIColor blackColor];
        _manager.configuration.navigationTitleColor = [UIColor whiteColor];
        _manager.configuration.selectVideoLimitSize = YES;
        _manager.configuration.limitVideoSize = 1024*1024*100;
        _manager.configuration.photoStyle = HXPhotoStyleDark;
        _manager.configuration.cellDarkSelectBgColor = rgba(76, 132, 255);
        _manager.configuration.languageType = HXPhotoLanguageTypeSc;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.videoMaximumSelectDuration = 60;
    }
    return _manager;
}

#pragma mark - HXPhotoViewController delegate
- (void)photoViewController:(HXPhotoViewController *)photoViewController
             didDoneAllList:(NSArray<HXPhotoModel *> *)allList
                     photos:(NSArray<HXPhotoModel *> *)photoList
                     videos:(NSArray<HXPhotoModel *> *)videoList
                   original:(BOOL)original{
    if (photoList.count > 0) {
        HXPhotoModel *photoModel = photoList.firstObject;
        self.headImage.image = photoModel.thumbPhoto;
        [self personalUploadHeadImgInterfaceWithImage:photoModel.thumbPhoto];
    }
}



@end
